package com.wephone.Student.ui;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import org.json.JSONException;
import org.json.JSONObject;

import android.R.bool;
import android.app.ActivityGroup;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.location.Criteria;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.media.audiofx.BassBoost.Settings;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.AnticipateOvershootInterpolator;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.easemob.EMGroupChangeListener;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatDB;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.chat.EMMessage;
import com.easemob.chat.TextMessageBody;
import com.easemob.chat.EMMessage.ChatType;
import com.easemob.chat.EMMessage.Type;

import com.easemob.util.EMLog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.umeng.analytics.MobclickAgent;
import com.wephone.Student.BaseApplication;
import com.wephone.Student.PushDemoReceiver;
import com.wephone.Student.R;
import com.wephone.Student.bean.BaseResponse;
import com.wephone.Student.bean.GroupDetailsResponse;
import com.wephone.Student.bean.GroupMessageResponse;
import com.wephone.Student.bean.LoginResponse;
import com.wephone.Student.bean.MyLiuxuequanCountResponse;
import com.wephone.Student.bean.SearchCollegeResponse;
import com.wephone.Student.bean.UserInfoResponse;
import com.wephone.Student.bean.data.CityData;
import com.wephone.Student.bean.data.CountryData;
import com.wephone.Student.bean.data.GroupInfo;
import com.wephone.Student.bean.data.GroupInfoData;
import com.wephone.Student.bean.data.GroupInvite;
import com.wephone.Student.bean.data.ProvinceData;
import com.wephone.Student.bean.data.SearchCollegeData;
import com.wephone.Student.bean.data.UserInfoData;
import com.wephone.Student.huanxin.Constant;
import com.wephone.Student.huanxin.activity.ChatHistoryActivity;
import com.wephone.Student.huanxin.db.InviteMessgeDao;
import com.wephone.Student.huanxin.db.UserDao;
import com.wephone.Student.huanxin.domain.InviteMessage;
import com.wephone.Student.huanxin.domain.InviteMessage.InviteMesageStatus;
import com.wephone.Student.huanxin.domain.User;
import com.wephone.Student.network.HttpClient;
import com.wephone.Student.network.MyResponseHandler;
import com.wephone.Student.util.Constants;
import com.wephone.Student.util.GPSTracker;
import com.wephone.Student.util.ShareReferenceUtil;
import com.wephone.Student.wheel.widget.OnWheelChangedListener;
import com.wephone.Student.wheel.widget.StringWheelAdapter;
import com.wephone.Student.wheel.widget.WheelView;
import com.wephone.Student.util.SegmentedGroup;

import com.igexin.sdk.PushManager;

public class MainTabBar extends ActivityGroup {
	private static final int TIME_AUTO_GET_DATA = 30 * 1000;
	private static Timer timer;
	private static long backClickTime = -1;
	// private LinearLayout layout_content;
	// private LinearLayout layout_menu;
	// private LinearLayout myLayout;
	// private int window_width;
	// private int MAX_WIDTH = 0;
	// private boolean hasMeasured = false;
	// private final int SLEEP_TIME = 5;
	// private final int SPEED = 30;
	private LinearLayout bodyLayout;
	private Button rightBtn;
	private TextView rightBtn2;
	private int currIdx;
	private TextView unreadLabel;
	public static boolean isFront = false;
	private int countryIdx;
	private int provinceIdx;
	private int cityIdx;
	private int homeIdx1;
	private int homeIdx2;
	private int locIdx1;
	private int locIdx2;
	private long searchTime;
	private List<SearchCollegeData> searchCollegeList = new ArrayList<SearchCollegeData>();
	private AutoCompleteTextView schoolInput;
	public static boolean needRefresh = false;
	private int times = 0;
	public static MainTabBar s_instance;
	private GPSTracker gps;

	public List<GroupInvite> invites = new ArrayList<GroupInvite>();
	public List<GroupInvite> inviteds = new ArrayList<GroupInvite>();

	private NewMessageBroadcastReceiver msgReceiver;
	public LocationClient mLocationClient = null;
	public BDLocationListener myListener = null;

	// private Handler handler = new Handler(){
	// @Override
	// public void handleMessage(Message msg) {
	// List<UserMessageListData> msgList = (List<UserMessageListData>)msg.obj;
	// if(msgList!=null && msgList.size()>0){
	// int msgCount = 0;
	// for(UserMessageListData msgData:msgList){
	// if(!msgData.isHasRead()){
	// msgCount = msgCount+msgData.getMsgCnt();
	// }
	// }
	// if(msgCount>0){
	// msgCountText.setVisibility(View.VISIBLE);
	// msgCountText.setText(""+msgCount);
	// }else{
	// msgCountText.setVisibility(View.GONE);
	// }
	// }
	// }
	// };

	private MyResponseHandler getHandler2() {
		MyResponseHandler handler = new MyResponseHandler(MainTabBar.this,
				BaseResponse.class) {
			@Override
			public void onSuccess(String result) {
				super.onSuccess(result);

				// if(getDataSuccess){
				//
				// }
			}
		};
		return handler;
	}

	AsyncHttpResponseHandler collegeHandler = new AsyncHttpResponseHandler() {
		@Override
		public void onFailure(Throwable arg0, String result) {
		}

		@Override
		public void onSuccess(String result) {
			if (!TextUtils.isEmpty(result)) {
				try {
					Gson gson = new Gson();
					SearchCollegeResponse response = (SearchCollegeResponse) gson
							.fromJson(result, SearchCollegeResponse.class);
					// System.out.println("---message---"+response.getErrorMsg());
					if (response.getErrNo() != null
							&& response.getErrNo().equals("0")) {
						if (response.getData() != null
								&& response.getData().size() > 0) {
							searchCollegeList.clear();
							searchCollegeList.addAll(response.getData());

							List<String> collegeNameArray = new ArrayList<String>();
							for (SearchCollegeData scd : searchCollegeList) {
								collegeNameArray.add(scd.getName());
							}
							ArrayAdapter<String> av = new ArrayAdapter<String>(
									MainTabBar.this,
									R.layout.include_college_dropdown_item,
									collegeNameArray);
							schoolInput.setAdapter(av);
							// schoolInput.showDropDown();
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	};

	@Override
	protected void onPause() {
		super.onPause();

		MobclickAgent.onPause(this);

		isFront = false;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		MobclickAgent.onResume(this);

		isFront = true;

		updateUnreadLabel();

		checkHasNewUserInfo();

		if (needRefresh && currIdx == 4) {
			needRefresh = false;
			SettingsActivity.needRefresh = true;
			showCurrentBody(0);
			showCurrentBody(4);
		}
		System.out.println("MainTabBar onResume");
		// new MessageListAsyncTask(getApplicationContext(), handler).execute();

		// locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
		// 1000, 1,
		// locationListener);
		mLocationClient = new LocationClient(this);
		// 设置定位条件
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true); // 是否打开GPS
		option.setCoorType("bd09ll"); // 设置返回值的坐标类型。
		option.setPriority(LocationClientOption.NetWorkFirst); // 设置定位优先级
		option.setProdName("LocationDemo"); // 设置产品线名称。强烈建议您使用自定义的产品线名称，方便我们以后为您提供更高效准确的定位服务。
		option.setScanSpan(10); // 设置定时定位的时间间隔。单位毫秒
		mLocationClient.setLocOption(option);

		// 注册位置监听器
		mLocationClient.registerLocationListener(new BDLocationListener() {

			@Override
			public void onReceiveLocation(BDLocation location) {
				// TODO Auto-generated method stub
				if (location == null) {
					return;
				}
				ShareReferenceUtil.saveLocationLatitude(
						getApplicationContext(), location.getLatitude()
								+ "");
				ShareReferenceUtil.saveLocationLontitude(
						getApplicationContext(),
						location.getLongitude() + "");
				
			}


		});
		mLocationClient.start();
		if (mLocationClient != null && mLocationClient.isStarted()){
			mLocationClient.requestLocation();
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mLocationClient.stop();
		// 注销广播接收者
		try {
			unregisterReceiver(msgReceiver);
		} catch (Exception e) {
		}
		try {
			unregisterReceiver(ackMessageReceiver);
		} catch (Exception e) {
		}

		if (timer != null) {
			timer.cancel();
			timer = null;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (requestCode == 2 && resultCode == 22) {
			startActivity(new Intent(getApplicationContext(),
					LoginActivity.class));
			finish();
		} else if (requestCode == 12 && resultCode == 11) {
			LiuXueQuanMainActivity.needRefresh = true;
			showCurrentBody(0);
			showCurrentBody(3);
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		s_instance = this;
		setContentView(R.layout.activity_main_tab_bar);

		PushManager.getInstance().initialize(getApplicationContext());

		init();
		SettingsActivity.tabRedPointView = findViewById(R.id.liuxuequan_status_red_point);

		// TODO Auto-generated method stub
		locationManager = (LocationManager) this
				.getSystemService(Context.LOCATION_SERVICE);
		locationListener = new LocationListener() {

			/**
			 * 位置信息变化时触发
			 */
			public void onLocationChanged(Location location) {

				Log.i(TAG, "时间：" + location.getTime());
				Log.i(TAG, "经度：" + location.getLongitude());
				Log.i(TAG, "纬度：" + location.getLatitude());
				Log.i(TAG, "海拔：" + location.getAltitude());
				// locationManager.removeUpdates(this);
				// locationManager.setTestProviderEnabled(provider, false);
			}

			/**
			 * GPS状态变化时触发
			 */
			public void onStatusChanged(String provider, int status,
					Bundle extras) {
				switch (status) {
				// GPS状态为可见时
				case LocationProvider.AVAILABLE:
					Log.i(TAG, "当前GPS状态为可见状态");
					break;
				// GPS状态为服务区外时
				case LocationProvider.OUT_OF_SERVICE:
					Log.i(TAG, "当前GPS状态为服务区外状态");
					break;
				// GPS状态为暂停服务时
				case LocationProvider.TEMPORARILY_UNAVAILABLE:
					Log.i(TAG, "当前GPS状态为暂停服务状态");
					break;
				}
			}

			/**
			 * GPS开启时触发
			 */
			public void onProviderEnabled(String provider) {

			}

			/**
			 * GPS禁用时触发
			 */
			public void onProviderDisabled(String provider) {

			}
		};

		// getLocation();
		uploadClientId();

		// receiver = new MyReceiver(new Handler()); // Create the receiver
		// registerReceiver(receiver, new IntentFilter("com.message")); //
		// Register receiver

		// sendBroadcast(new Intent("com.message")); // Send an example Intent
	}

	public static void uploadClientId() {
		if (PushDemoReceiver.clientId != null
				&& PushDemoReceiver.clientId.length() > 0) {
			RequestParams params = new RequestParams();
			params.put("uId", BaseActivity.getMyInfo(MainTabBar.s_instance)
					.getuId());
			params.put("client_id", PushDemoReceiver.clientId);
			params.put("token", "111");
			params.put("client", "2");
			HttpClient.getInstance().get(
					Constants.API_SET_USER_TOKEN,
					params,
					new MyResponseHandler(MainTabBar.s_instance,
							BaseResponse.class) {
						@Override
						public void onSuccess(String result) {

						}
					});
		}
	}

	private void init() {
		bodyLayout = (LinearLayout) findViewById(R.id.body_content);
		// layout_content = (LinearLayout)findViewById(R.id.main_top_layout);
		// layout_menu = (LinearLayout)findViewById(R.id.layout_menu);
		// myLayout = (LinearLayout)findViewById(R.id.mylayout);
		rightBtn = (Button) findViewById(R.id.btn_top_right);
		unreadLabel = (TextView) findViewById(R.id.tab_msg_count_dot);
		rightBtn2 = (TextView) findViewById(R.id.btn_top_right2);

		rightBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (currIdx == 4) {
					new AlertDialog.Builder(MainTabBar.this)
							.setTitle("提示")
							.setMessage("确定退出登录吗？")
							.setNegativeButton("取消",
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
										}
									})
							.setPositiveButton("确定",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int whichButton) {
											ShareReferenceUtil
													.saveUserInfoJson(
															getApplicationContext(),
															"");
											startActivity(new Intent(
													getApplicationContext(),
													LoginActivity.class));
											finish();
											// reg push
											RequestParams params = new RequestParams();
											params.put(
													"uId",
													BaseActivity
															.getMyInfo(
																	getApplicationContext())
															.getuId());
											params.put("uPushIdentifier", "0");
											HttpClient.getInstance().get(
													Constants.API_REG_PUSH_URL,
													params, getHandler2());

											BaseApplication.getInstance()
													.logout();
											ShareReferenceUtil
													.savePushUserInfoJson(
															getApplicationContext(),
															null);
										}
									}).show();
					// }else if(currIdx==1){
					// MessageActivity.needRefresh = true;
					// showCurrentBody(4);
					// showCurrentBody(1);
				} else if (currIdx == 3) {
					// FocusActivity.needRefresh = true;
					// showCurrentBody(4);
					// showCurrentBody(3);
					startActivityForResult(new Intent(getApplicationContext(),
							CreateLiuxuequanActivity.class), 12);
				} else if (currIdx == 0) {
					// showOnlineFilterDialog(getApplicationContext());
				}
			}
		});

		rightBtn2.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (currIdx == 3) {
					startActivity(new Intent(getApplicationContext(),
							ZhidaoSearchActivity.class));
				} else {
					startActivityForResult(new Intent(getApplicationContext(),
							Settings2Activity.class), 2);
				}
			}
		});

		// rightBtn2.setOnClickListener(new View.OnClickListener() {
		// @Override
		// public void onClick(View arg0) {
		// // System.out.println("----currIdx----"+currIdx);
		// if(currIdx==0){
		// OnlineActivity.needRefresh = true;
		// OnlineActivity.isDoSearch = false;
		// OnlineActivity.country = "";
		// OnlineActivity.city = "";
		// OnlineActivity.school = "";
		// OnlineActivity.loc = "";
		// OnlineActivity.home = "";
		// OnlineActivity.type = "";
		// OnlineActivity.uGender = "";
		// showCurrentBody(4);
		// showCurrentBody(0);
		// }
		// }
		// });

		findViewById(R.id.btn_popup_menu_open).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						// RelativeLayout.LayoutParams layoutParams =
						// (RelativeLayout.LayoutParams)
						// layout_content.getLayoutParams();
						// if (layoutParams.rightMargin >= 0) {
						// new AsynMove().execute(-SPEED);
						// } else {
						// new AsynMove().execute(SPEED);
						// }
						showPopUp();
					}
				});
		// getMAX_WIDTH();

		findViewById(R.id.tab_bottom_menu_layout_1).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						showCurrentBody(0);
					}
				});
		findViewById(R.id.tab_bottom_menu_layout_2).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						showCurrentBody(1);
					}
				});
		findViewById(R.id.tab_bottom_menu_layout_3).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						showCurrentBody(2);
					}
				});
		findViewById(R.id.tab_bottom_menu_layout_4).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						showCurrentBody(3);
					}
				});
		findViewById(R.id.tab_bottom_menu_layout_5).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						showCurrentBody(4);
					}
				});
		// findViewById(R.id.left_menu_item_1).setOnClickListener(new
		// View.OnClickListener() {
		// @Override
		// public void onClick(View v) {
		// RelativeLayout.LayoutParams layoutParams =
		// (RelativeLayout.LayoutParams) layout_content.getLayoutParams();
		// if (layoutParams.rightMargin<0) {
		// new AsynMove().execute(SPEED);
		// }
		// startActivity(new
		// Intent(getApplicationContext(),FanliActivity.class));
		// }
		// });
		// findViewById(R.id.left_menu_item_2).setOnClickListener(new
		// View.OnClickListener() {
		// @Override
		// public void onClick(View v) {
		// RelativeLayout.LayoutParams layoutParams =
		// (RelativeLayout.LayoutParams) layout_content.getLayoutParams();
		// if (layoutParams.rightMargin<0) {
		// new AsynMove().execute(SPEED);
		// }
		// startActivity(new
		// Intent(getApplicationContext(),FlyTogetherActivity.class));
		// }
		// });
		// findViewById(R.id.left_menu_item_3).setOnClickListener(new
		// View.OnClickListener() {
		// @Override
		// public void onClick(View v) {
		// RelativeLayout.LayoutParams layoutParams =
		// (RelativeLayout.LayoutParams) layout_content.getLayoutParams();
		// if (layoutParams.rightMargin<0) {
		// new AsynMove().execute(SPEED);
		// }
		// startActivity(new
		// Intent(getApplicationContext(),HouseInfoListActivity.class));
		// }
		// });
		// findViewById(R.id.left_menu_item_4).setOnClickListener(new
		// View.OnClickListener() {
		// @Override
		// public void onClick(View v) {
		// RelativeLayout.LayoutParams layoutParams =
		// (RelativeLayout.LayoutParams) layout_content.getLayoutParams();
		// if (layoutParams.rightMargin<0) {
		// new AsynMove().execute(SPEED);
		// }
		// startActivity(new
		// Intent(getApplicationContext(),MutualTransactionActivity.class));
		// }
		// });
		// findViewById(R.id.left_menu_item_5).setOnClickListener(new
		// View.OnClickListener() {
		// @Override
		// public void onClick(View v) {
		// RelativeLayout.LayoutParams layoutParams =
		// (RelativeLayout.LayoutParams) layout_content.getLayoutParams();
		// if (layoutParams.rightMargin<0) {
		// new AsynMove().execute(SPEED);
		// }
		// startActivity(new
		// Intent(getApplicationContext(),GlobalPurchasingActivity.class));
		// }
		// });

		OnlineActivity.needRefresh = true;
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			boolean showChatHistoryPage = bundle.getBoolean(
					"showChatHistoryPage", false);
			if (showChatHistoryPage) {
				ChatHistoryActivity.needRefresh = true;
				showCurrentBody(1);
			} else {
				showCurrentBody(0);
			}
		} else {
			showCurrentBody(0);
		}

		// 注册一个接收消息的BroadcastReceiver
		msgReceiver = new NewMessageBroadcastReceiver();
		IntentFilter intentFilter = new IntentFilter(EMChatManager
				.getInstance().getNewMessageBroadcastAction());
		intentFilter.setPriority(3);
		registerReceiver(msgReceiver, intentFilter);

		// 注册一个ack回执消息的BroadcastReceiver
		IntentFilter ackMessageIntentFilter = new IntentFilter(EMChatManager
				.getInstance().getAckMessageBroadcastAction());
		ackMessageIntentFilter.setPriority(3);
		registerReceiver(ackMessageReceiver, ackMessageIntentFilter);
		// 通知sdk，UI 已经初始化完毕，注册了相应的receiver和listener, 可以接受broadcast了

		EMGroupManager.getInstance().addGroupChangeListener(
				new MyGroupChangeListener());

		inviteMessgeDao = new InviteMessgeDao(this);
		userDao = new UserDao(this);

		EMChat.getInstance().setAppInited();

		// setContactListener监听联系人的变化等
		// EMContactManager.getInstance().setContactListener(new
		// MyContactListener());
		// 注册一个监听连接状态的listener
		// EMChatManager.getInstance().addConnectionListener(new
		// MyConnectionListener());
		// 注册群聊相关的listener
		// EMGroupManager.getInstance().addGroupChangeListener(new
		// MyGroupChangeListener());

		if (timer != null) {
			timer.cancel();
			timer = null;
		}
		timer = new Timer();
		TimerTask task = new TimerTask() {
			@Override
			public void run() {
				handler.sendEmptyMessage(11);
			}
		};
		timer.schedule(task, 2000, TIME_AUTO_GET_DATA);
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 11) {
				RequestParams params3 = new RequestParams();
				params3.put("uId",
						BaseActivity.getMyInfo(getApplicationContext())
								.getuId());
				HttpClient.getInstance().get(
						Constants.API_GET_STUDY_CIRCLE_INFO_URL, params3,
						getHandler8());
			}
		}
	};

	private MyResponseHandler getHandler8() {
		MyResponseHandler handler = new MyResponseHandler(MainTabBar.this,
				MyLiuxuequanCountResponse.class) {
			@Override
			public void onSuccess(String result) {
				super.onSuccess(result);

				if (getDataSuccess) {
					MyLiuxuequanCountResponse res = (MyLiuxuequanCountResponse) response;
					if (res.getData().getCount() > 0) {
						// TODO
						findViewById(R.id.liuxuequan_status_red_point)
								.setVisibility(View.VISIBLE);
						if (currIdx != 4) {
							SettingsActivity.needRefresh = true;
						} else {
							SettingsActivity.needRefresh = true;
							showCurrentBody(0);
							showCurrentBody(4);
						}
					}
				}
			}
		};
		return handler;
	}

	// private void getMAX_WIDTH() {
	// ViewTreeObserver viewTreeObserver = layout_content.getViewTreeObserver();
	// viewTreeObserver.addOnPreDrawListener(new OnPreDrawListener() {
	// @Override
	// public boolean onPreDraw() {
	// if (!hasMeasured) {
	// window_width = getWindowManager().getDefaultDisplay().getWidth();
	// MAX_WIDTH = layout_menu.getWidth();
	// RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)
	// layout_content.getLayoutParams();
	// RelativeLayout.LayoutParams layoutParams_1 =
	// (RelativeLayout.LayoutParams) layout_menu.getLayoutParams();
	// ViewGroup.LayoutParams layoutParams_2 = myLayout.getLayoutParams();
	// layoutParams.width = window_width;
	// layout_content.setLayoutParams(layoutParams);
	//
	// layoutParams_1.rightMargin = window_width;
	// layout_menu.setLayoutParams(layoutParams_1);
	//
	// layoutParams_2.width = MAX_WIDTH;
	// myLayout.setLayoutParams(layoutParams_2);
	// hasMeasured = true;
	// }
	// return true;
	// }
	// });
	// }

	// private class AsynMove extends AsyncTask<Integer, Integer, Void> {
	// @Override
	// protected Void doInBackground(Integer... params) {
	// int times = 0;
	// if (MAX_WIDTH % Math.abs(params[0]) == 0){
	// times = MAX_WIDTH / Math.abs(params[0]);
	// }else{
	// times = MAX_WIDTH / Math.abs(params[0]) + 1;
	// }
	// for (int i = 0; i < times; i++) {
	// publishProgress(params[0]);
	// try {
	// Thread.sleep(SLEEP_TIME);
	// } catch (InterruptedException e) {
	// e.printStackTrace();
	// }
	// }
	// return null;
	// }
	//
	// @Override
	// protected void onProgressUpdate(Integer... values) {
	// RelativeLayout.LayoutParams layoutParams =
	// (RelativeLayout.LayoutParams)layout_content.getLayoutParams();
	// RelativeLayout.LayoutParams layoutParams_1 =
	// (RelativeLayout.LayoutParams)layout_menu.getLayoutParams();
	// if (values[0] > 0) {
	// layoutParams.rightMargin = Math.min(layoutParams.rightMargin + values[0],
	// 0);
	// layoutParams_1.rightMargin = Math.min(layoutParams_1.rightMargin +
	// values[0], window_width);
	// } else {
	// layoutParams.rightMargin = Math.max(layoutParams.rightMargin + values[0],
	// -MAX_WIDTH);
	// layoutParams_1.rightMargin = Math.max(layoutParams_1.rightMargin +
	// values[0], window_width - MAX_WIDTH);
	// }
	// layout_menu.setLayoutParams(layoutParams_1);
	// layout_content.setLayoutParams(layoutParams);
	// }
	// }

	private void showCurrentBody(int idx) {
		Intent intent = getIntentByIndex(idx);
		displayIntent(intent, idx);
	}

	private void displayIntent(Intent intent, int idx) {
		currIdx = idx;
		String key = intent.getStringExtra("key");
		View view = getLocalActivityManager().startActivity(key, intent)
				.getDecorView();
		bodyLayout.removeAllViews();
		bodyLayout.addView(view);
		if (idx == 0) {
			rightBtn.setText("");
			rightBtn.setBackgroundResource(R.drawable.btn_filter_selected);
			rightBtn.setVisibility(View.GONE);
			rightBtn2.setVisibility(View.GONE);
			// rightBtn2.setVisibility(View.VISIBLE);
			SegmentedGroup sgp = (SegmentedGroup) findViewById(R.id.segMain);
			sgp.setVisibility(View.VISIBLE);
			sgp.setTintColor(Color.parseColor("#FFFFFF"),
					Color.parseColor("#DF9B3D"));
			RadioButton topBtnNew = (RadioButton) findViewById(R.id.topBtnNew);

			RadioButton topBtnNear = (RadioButton) findViewById(R.id.topBtnNear);
			RadioButton topBtnGroup = (RadioButton) findViewById(R.id.topBtnGroup);
			RadioButton topBtnSearch = (RadioButton) findViewById(R.id.topBtnSearch);
			topBtnNew.setChecked(true);
			topBtnNew.setOnCheckedChangeListener(new OnCheckedChangeListener() {

				@Override
				public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
					// TODO Auto-generated method stub
					if (arg1) {
						OnlineActivity.s_instance.showTab(1);
						// Toast.makeText(MainTabBar.this, "zuixinchecked",
						// Toast.LENGTH_SHORT).show();
					} else {

					}
				}

			});
			topBtnNear
					.setOnCheckedChangeListener(new OnCheckedChangeListener() {

						@Override
						public void onCheckedChanged(CompoundButton arg0,
								boolean arg1) {
							// TODO Auto-generated method stub
							if (arg1) {
								OnlineActivity.s_instance.showTab(2);
								// Toast.makeText(getApplicationContext(), "2",
								// Toast.LENGTH_SHORT).show();
							} else {

							}
						}

					});
			topBtnGroup
					.setOnCheckedChangeListener(new OnCheckedChangeListener() {

						@Override
						public void onCheckedChanged(CompoundButton arg0,
								boolean arg1) {
							// TODO Auto-generated method stub
							if (arg1) {
								OnlineActivity.s_instance.showTab(3);
							} else {

							}
						}

					});
			topBtnSearch
					.setOnCheckedChangeListener(new OnCheckedChangeListener() {

						@Override
						public void onCheckedChanged(CompoundButton arg0,
								boolean arg1) {
							// TODO Auto-generated method stub
							if (arg1) {
								OnlineActivity.s_instance.showTab(4);
							} else {

							}
						}
					});
			((TextView) findViewById(R.id.top_bar_title))
					.setVisibility(View.GONE);
			((ImageView) findViewById(R.id.tab_menu_1))
					.setImageResource(R.drawable.bottom_bar_1_focus);
			((ImageView) findViewById(R.id.tab_menu_2))
					.setImageResource(R.drawable.bottom_bar_2);
			((ImageView) findViewById(R.id.tab_menu_3))
					.setImageResource(R.drawable.bottom_bar_3);
			((ImageView) findViewById(R.id.tab_menu_4))
					.setImageResource(R.drawable.bottom_bar_4);
			((ImageView) findViewById(R.id.tab_menu_5))
					.setImageResource(R.drawable.bottom_bar_5);
			((TextView) findViewById(R.id.tab_menu_text_1)).setTextColor(Color
					.rgb(255, 140, 00));
			((TextView) findViewById(R.id.tab_menu_text_2)).setTextColor(Color
					.rgb(30, 38, 61));
			// ((TextView)findViewById(R.id.tab_menu_text_3)).setTextColor(Color.rgb(30,
			// 38, 61));
			((TextView) findViewById(R.id.tab_menu_text_4)).setTextColor(Color
					.rgb(30, 38, 61));
			((TextView) findViewById(R.id.tab_menu_text_5)).setTextColor(Color
					.rgb(30, 38, 61));
		} else if (idx == 1) {
			// rightBtn.setText(R.string.btn_refresh);
			// rightBtn.setBackgroundResource(R.drawable.btn_liuxuequan_camera_selected);
			// rightBtn.setVisibility(View.VISIBLE);
			rightBtn.setVisibility(View.GONE);
			SegmentedGroup sgp = (SegmentedGroup) findViewById(R.id.segMain);
			sgp.setVisibility(View.GONE);
			rightBtn2.setVisibility(View.GONE);

			// rightBtn2.setVisibility(View.GONE);
			((TextView) findViewById(R.id.top_bar_title))
					.setVisibility(View.VISIBLE);
			((TextView) findViewById(R.id.top_bar_title))
					.setText(R.string.main_top_bar_title_2);
			((ImageView) findViewById(R.id.tab_menu_1))
					.setImageResource(R.drawable.bottom_bar_1);
			((ImageView) findViewById(R.id.tab_menu_2))
					.setImageResource(R.drawable.bottom_bar_2_focus);
			((ImageView) findViewById(R.id.tab_menu_3))
					.setImageResource(R.drawable.bottom_bar_3);
			((ImageView) findViewById(R.id.tab_menu_4))
					.setImageResource(R.drawable.bottom_bar_4);
			((ImageView) findViewById(R.id.tab_menu_5))
					.setImageResource(R.drawable.bottom_bar_5);
			((TextView) findViewById(R.id.tab_menu_text_1)).setTextColor(Color
					.rgb(30, 38, 61));
			((TextView) findViewById(R.id.tab_menu_text_2)).setTextColor(Color
					.rgb(255, 140, 00));
			// ((TextView)findViewById(R.id.tab_menu_text_3)).setTextColor(Color.rgb(30,
			// 38, 61));
			((TextView) findViewById(R.id.tab_menu_text_4)).setTextColor(Color
					.rgb(30, 38, 61));
			((TextView) findViewById(R.id.tab_menu_text_5)).setTextColor(Color
					.rgb(30, 38, 61));
		} else if (idx == 2) {
			rightBtn.setText(R.string.btn_options);
			rightBtn.setBackgroundResource(R.drawable.btn_top_right_selected);
			rightBtn.setVisibility(View.VISIBLE);
			rightBtn2.setVisibility(View.GONE);
			SegmentedGroup sgp = (SegmentedGroup) findViewById(R.id.segMain);
			sgp.setVisibility(View.GONE);
			// rightBtn2.setVisibility(View.VISIBLE);
			((TextView) findViewById(R.id.top_bar_title))
					.setVisibility(View.VISIBLE);
			((TextView) findViewById(R.id.top_bar_title))
					.setText(R.string.main_top_bar_title_3);
			((ImageView) findViewById(R.id.tab_menu_1))
					.setImageResource(R.drawable.bottom_bar_1);
			((ImageView) findViewById(R.id.tab_menu_2))
					.setImageResource(R.drawable.bottom_bar_2);
			((ImageView) findViewById(R.id.tab_menu_3))
					.setImageResource(R.drawable.bottom_bar_3_focus);
			((ImageView) findViewById(R.id.tab_menu_4))
					.setImageResource(R.drawable.bottom_bar_4);
			((ImageView) findViewById(R.id.tab_menu_5))
					.setImageResource(R.drawable.bottom_bar_5);
			((TextView) findViewById(R.id.tab_menu_text_1)).setTextColor(Color
					.rgb(30, 38, 61));
			((TextView) findViewById(R.id.tab_menu_text_2)).setTextColor(Color
					.rgb(30, 38, 61));
			// ((TextView)findViewById(R.id.tab_menu_text_3)).setTextColor(Color.rgb(255,
			// 140, 00));
			((TextView) findViewById(R.id.tab_menu_text_4)).setTextColor(Color
					.rgb(30, 38, 61));
			((TextView) findViewById(R.id.tab_menu_text_5)).setTextColor(Color
					.rgb(30, 38, 61));
		} else if (idx == 3) {
			// rightBtn.setText(R.string.btn_refresh);
			// rightBtn.setBackgroundResource(R.drawable.btn_top_right_selected);
			// rightBtn.setVisibility(View.VISIBLE);
			// rightBtn.setVisibility(View.GONE);
			rightBtn.setBackgroundResource(R.drawable.btn_liuxuequan_camera_selected);
			rightBtn.setVisibility(View.VISIBLE);
			SegmentedGroup sgp = (SegmentedGroup) findViewById(R.id.segMain);
			sgp.setVisibility(View.GONE);
			// rightBtn2.setText("提问");
			// rightBtn2.setVisibility(View.VISIBLE);
			rightBtn2.setVisibility(View.GONE);
			((TextView) findViewById(R.id.top_bar_title))
					.setVisibility(View.VISIBLE);
			((TextView) findViewById(R.id.top_bar_title))
					.setText(R.string.main_top_bar_title_4);
			((ImageView) findViewById(R.id.tab_menu_1))
					.setImageResource(R.drawable.bottom_bar_1);
			((ImageView) findViewById(R.id.tab_menu_2))
					.setImageResource(R.drawable.bottom_bar_2);
			((ImageView) findViewById(R.id.tab_menu_3))
					.setImageResource(R.drawable.bottom_bar_3);
			((ImageView) findViewById(R.id.tab_menu_4))
					.setImageResource(R.drawable.bottom_bar_4_focus);
			((ImageView) findViewById(R.id.tab_menu_5))
					.setImageResource(R.drawable.bottom_bar_5);
			((TextView) findViewById(R.id.tab_menu_text_1)).setTextColor(Color
					.rgb(30, 38, 61));
			((TextView) findViewById(R.id.tab_menu_text_2)).setTextColor(Color
					.rgb(30, 38, 61));
			// ((TextView)findViewById(R.id.tab_menu_text_3)).setTextColor(Color.rgb(30,
			// 38, 61));
			((TextView) findViewById(R.id.tab_menu_text_4)).setTextColor(Color
					.rgb(255, 140, 00));
			((TextView) findViewById(R.id.tab_menu_text_5)).setTextColor(Color
					.rgb(30, 38, 61));
		} else if (idx == 4) {
			// findViewById(R.id.liuxuequan_status_red_point).setVisibility(View.GONE);
			rightBtn.setVisibility(View.GONE);
			SegmentedGroup sgp = (SegmentedGroup) findViewById(R.id.segMain);
			sgp.setVisibility(View.GONE);
			rightBtn2.setText("设置");
			rightBtn2.setVisibility(View.VISIBLE);
			// rightBtn2.setVisibility(View.GONE);
			((TextView) findViewById(R.id.top_bar_title)).setText("我");
			((TextView) findViewById(R.id.top_bar_title))
					.setVisibility(View.VISIBLE);
			((ImageView) findViewById(R.id.tab_menu_1))
					.setImageResource(R.drawable.bottom_bar_1);
			((ImageView) findViewById(R.id.tab_menu_2))
					.setImageResource(R.drawable.bottom_bar_2);
			((ImageView) findViewById(R.id.tab_menu_3))
					.setImageResource(R.drawable.bottom_bar_3);
			((ImageView) findViewById(R.id.tab_menu_4))
					.setImageResource(R.drawable.bottom_bar_4);
			((ImageView) findViewById(R.id.tab_menu_5))
					.setImageResource(R.drawable.bottom_bar_5_focus);
			((TextView) findViewById(R.id.tab_menu_text_1)).setTextColor(Color
					.rgb(30, 38, 61));
			((TextView) findViewById(R.id.tab_menu_text_2)).setTextColor(Color
					.rgb(30, 38, 61));
			// ((TextView)findViewById(R.id.tab_menu_text_3)).setTextColor(Color.rgb(30,
			// 38, 61));
			((TextView) findViewById(R.id.tab_menu_text_4)).setTextColor(Color
					.rgb(30, 38, 61));
			((TextView) findViewById(R.id.tab_menu_text_5)).setTextColor(Color
					.rgb(255, 140, 00));
		}
	}

	private TextView SegmentGroup(TextView findViewById) {
		// TODO Auto-generated method stub
		return null;
	}

	private Intent getIntentByIndex(int idx) {
		Intent intent = getIntent1();
		if (idx == 1) {
			intent = getIntent2();
		} else if (idx == 2) {
			intent = getIntent3();
		} else if (idx == 3) {
			intent = getIntent4();
		} else if (idx == 4) {
			intent = getIntent5();
		}
		return intent;
	}

	private Intent getIntent1() {
		// OnlineActivity.needRefresh = true;
		Intent intent = new Intent(MainTabBar.this, OnlineActivity.class);
		intent.putExtra("key", "index1");
		return intent;
	}

	private Intent getIntent2() {
		// MessageActivity.needRefresh = true;
		// Intent intent = new Intent(MainTabBar.this, MessageActivity.class);
		// intent.putExtra("key", "index2");
		ChatHistoryActivity.needRefresh = true;
		Intent intent = new Intent(MainTabBar.this, ChatHistoryActivity.class);
		intent.putExtra("key", "index5");
		return intent;
	}

	private Intent getIntent3() {
		Intent intent = new Intent(MainTabBar.this, GroupActivity.class);
		intent.putExtra("key", "index3");
		return intent;
	}

	private Intent getIntent4() {
		// FocusActivity.needRefresh = true;
		// Intent intent = new Intent(MainTabBar.this, FocusActivity.class);
		Intent intent = new Intent(MainTabBar.this,
				LiuXueQuanMainActivity.class);
		intent.putExtra("key", "index4");
		return intent;
	}

	private Intent getIntent5() {
		Intent intent = new Intent(MainTabBar.this, SettingsActivity.class);
		intent.putExtra("key", "index5");
		return intent;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			long nowTime = System.currentTimeMillis();
			if (backClickTime <= 0 || nowTime - backClickTime > 2000) {
				backClickTime = nowTime;
				Toast.makeText(getApplicationContext(), "再按一次 退出程序",
						Toast.LENGTH_SHORT).show();
			} else {
				finish();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void showOnlineFilterDialog(Context context) {
		final View inputView = getLayoutInflater().inflate(
				R.layout.dialog_online_filter_view, null);
		final TextView inputEdit1 = (TextView) inputView
				.findViewById(R.id.dialog_filter_input_1);
		// inputEdit1.setText(OnlineActivity.country);
		final TextView inputEdit2 = (TextView) inputView
				.findViewById(R.id.dialog_filter_input_2);
		// inputEdit2.setText(OnlineActivity.city);
		schoolInput = (AutoCompleteTextView) inputView
				.findViewById(R.id.dialog_filter_input_3);
		schoolInput.setText(OnlineActivity.school);
		schoolInput.addTextChangedListener(new TextWatcher() {
			@Override
			public void afterTextChanged(Editable arg0) {
				long nowTime = System.currentTimeMillis();
				if (nowTime - searchTime > 100) {
					searchTime = nowTime;
					RequestParams params = new RequestParams();
					params.put("name", schoolInput.getText().toString());
					HttpClient.getInstance().get2(
							Constants.API_SEARCH_COLLEGE_URL, params,
							collegeHandler);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
			}

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
			}
		});
		final TextView inputEdit4 = (TextView) inputView
				.findViewById(R.id.dialog_filter_input_4);
		final TextView inputEdit5 = (TextView) inputView
				.findViewById(R.id.dialog_filter_input_5);
		inputEdit1.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				showChooseCountryDialog(
						getString(R.string.dialog_online_filter_hint_1),
						inputEdit1, inputEdit2);
			}
		});
		inputEdit2.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (TextUtils.isEmpty(inputEdit1.getText().toString())) {
					Toast.makeText(getApplicationContext(), "请先选择曾经山楂的国家",
							Toast.LENGTH_SHORT).show();
				} else {
					showChooseCountryDialog2(
							getString(R.string.dialog_online_filter_hint_2),
							inputEdit2);
				}
			}
		});
		inputEdit4.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				showChooseCountryDialog4(
						getString(R.string.dialog_online_filter_hint_4),
						inputEdit4);
			}
		});
		inputEdit5.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				showChooseCountryDialog3(
						getString(R.string.dialog_online_filter_hint_5),
						inputEdit5);
			}
		});
		AlertDialog.Builder builder = new AlertDialog.Builder(MainTabBar.this);
		builder.setTitle("搜索");
		builder.setView(inputView);
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				EditText inputEdit0 = (EditText) inputView
						.findViewById(R.id.dialog_filter_input_0);
				String nameStr = inputEdit0.getText().toString();
				OnlineActivity.uName = nameStr;
				TextView inputEdit1 = (TextView) inputView
						.findViewById(R.id.dialog_filter_input_1);
				String countryStr = inputEdit1.getText().toString();
				OnlineActivity.country = countryStr;
				TextView inputEdit2 = (TextView) inputView
						.findViewById(R.id.dialog_filter_input_2);
				String cityStr = inputEdit2.getText().toString();
				OnlineActivity.city = cityStr;
				AutoCompleteTextView inputEdit3 = (AutoCompleteTextView) inputView
						.findViewById(R.id.dialog_filter_input_3);
				String schoolStr = inputEdit3.getText().toString();
				OnlineActivity.school = schoolStr;
				TextView inputEdit4 = (TextView) inputView
						.findViewById(R.id.dialog_filter_input_4);
				String locStr = inputEdit4.getText().toString();
				OnlineActivity.loc = locStr;
				TextView inputEdit5 = (TextView) inputView
						.findViewById(R.id.dialog_filter_input_5);
				String homeStr = inputEdit5.getText().toString();
				OnlineActivity.home = homeStr;
				Spinner opsSpinner = (Spinner) inputView
						.findViewById(R.id.dialog_filter_spinner);
				if (opsSpinner.getSelectedItemPosition() == 1) {
					OnlineActivity.type = "Foreign";
				} else if (opsSpinner.getSelectedItemPosition() == 2) {
					OnlineActivity.type = "Returnees";
				} else if (opsSpinner.getSelectedItemPosition() == 3) {
					OnlineActivity.type = "PlanGoOut";
				} else {
					OnlineActivity.type = "";
				}
				RadioButton genderRadio1 = (RadioButton) inputView
						.findViewById(R.id.gender_radio_1);
				RadioButton genderRadio2 = (RadioButton) inputView
						.findViewById(R.id.gender_radio_2);
				if (genderRadio1.isChecked()) {
					OnlineActivity.uGender = "-1";
				} else if (genderRadio2.isChecked()) {
					OnlineActivity.uGender = "0";
				} else {
					OnlineActivity.uGender = "1";
				}
				OnlineActivity.needRefresh = true;
				OnlineActivity.isDoSearch = true;
				showCurrentBody(4);
				showCurrentBody(0);
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
			}
		});
		builder.show();
	}

	// @Override
	// protected void onNewIntent(Intent intent) {
	// if(intent.getAction()!=null && intent.getAction().equals("refreshMsg")){
	// new MessageListAsyncTask(getApplicationContext(), handler).execute();
	// }else{
	// MessageActivity.needRefresh = true;
	// showCurrentBody(4);
	// showCurrentBody(1);
	// }
	// }

	private void showChooseCountryDialog(String title,
			final TextView inputEdit1, final TextView inputEdit2) {
		View inputView = getLayoutInflater().inflate(
				R.layout.dialog_wheel_1_view, null);
		final WheelView wheel = (WheelView) inputView
				.findViewById(R.id.wheel_1);
		List<String> countryList = new ArrayList<String>();
		for (CountryData cd : BaseActivity
				.getCountryList(getApplicationContext())) {
			countryList.add(cd.getN());
		}
		wheel.setAdapter(new StringWheelAdapter(countryList));
		wheel.setCurrentItem(countryIdx);
		wheel.setCyclic(true);
		wheel.setInterpolator(new AnticipateOvershootInterpolator());
		AlertDialog.Builder builder = new AlertDialog.Builder(MainTabBar.this);
		builder.setTitle(title);
		builder.setView(inputView);
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				provinceIdx = 0;
				cityIdx = 0;
				inputEdit2.setText("");
				countryIdx = wheel.getCurrentItem();
				inputEdit1.setText(BaseActivity
						.getCountryList(getApplicationContext())
						.get(countryIdx).getN());
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
			}
		});
		builder.show();
	}

	private void showChooseCountryDialog2(String title,
			final TextView inputEdit2) {
		View inputView = getLayoutInflater().inflate(
				R.layout.dialog_wheel_2_view, null);
		final WheelView wheel1 = (WheelView) inputView
				.findViewById(R.id.wheel_1);
		final WheelView wheel2 = (WheelView) inputView
				.findViewById(R.id.wheel_2);

		List<String> provinceList = new ArrayList<String>();
		for (ProvinceData cd : BaseActivity
				.getCountryList(getApplicationContext()).get(countryIdx).getP()) {
			provinceList.add(cd.getN());
		}
		wheel1.setAdapter(new StringWheelAdapter(provinceList));
		wheel1.setCurrentItem(provinceIdx);
		wheel1.setCyclic(true);
		wheel1.setInterpolator(new AnticipateOvershootInterpolator());
		wheel1.addChangingListener(new OnWheelChangedListener() {
			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				provinceIdx = newValue;
				cityIdx = 0;

				List<String> cityList = new ArrayList<String>();
				for (CityData cd : BaseActivity
						.getCountryList(getApplicationContext())
						.get(countryIdx).getP().get(provinceIdx).getC()) {
					cityList.add(cd.getN());
				}
				wheel2.setAdapter(new StringWheelAdapter(cityList));
				wheel2.setCurrentItem(cityIdx);
			}
		});

		List<String> cityList = new ArrayList<String>();
		for (CityData cd : BaseActivity.getCountryList(getApplicationContext())
				.get(countryIdx).getP().get(provinceIdx).getC()) {
			cityList.add(cd.getN());
		}
		wheel2.setAdapter(new StringWheelAdapter(cityList));
		wheel2.setCurrentItem(cityIdx);
		wheel2.setCyclic(true);
		wheel2.setInterpolator(new AnticipateOvershootInterpolator());

		AlertDialog.Builder builder = new AlertDialog.Builder(MainTabBar.this);
		builder.setTitle(title);
		builder.setView(inputView);
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				provinceIdx = wheel1.getCurrentItem();
				cityIdx = wheel2.getCurrentItem();
				if (TextUtils.isEmpty(BaseActivity
						.getCountryList(getApplicationContext())
						.get(countryIdx).getP().get(provinceIdx).getN())) {
					if (TextUtils.isEmpty(BaseActivity
							.getCountryList(getApplicationContext())
							.get(countryIdx).getP().get(provinceIdx).getC()
							.get(cityIdx).getN())) {
						inputEdit2.setText(BaseActivity
								.getCountryList(getApplicationContext())
								.get(countryIdx).getN());
					} else {
						inputEdit2.setText(BaseActivity
								.getCountryList(getApplicationContext())
								.get(countryIdx).getP().get(provinceIdx).getC()
								.get(cityIdx).getN());
					}
				} else {
					inputEdit2.setText(BaseActivity
							.getCountryList(getApplicationContext())
							.get(countryIdx).getP().get(provinceIdx).getN()
							+ " "
							+ BaseActivity
									.getCountryList(getApplicationContext())
									.get(countryIdx).getP().get(provinceIdx)
									.getC().get(cityIdx).getN());
				}
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
			}
		});
		builder.setNeutralButton("清空", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				inputEdit2.setText("");
				provinceIdx = 0;
				cityIdx = 0;
			}
		});
		builder.show();
	}

	private void showChooseCountryDialog3(String title,
			final TextView inputEdit3) {
		View inputView = getLayoutInflater().inflate(
				R.layout.dialog_wheel_2_view, null);
		final WheelView wheel1 = (WheelView) inputView
				.findViewById(R.id.wheel_1);
		final WheelView wheel2 = (WheelView) inputView
				.findViewById(R.id.wheel_2);

		List<String> provinceList = new ArrayList<String>();
		for (ProvinceData cd : BaseActivity
				.getCountryList(getApplicationContext()).get(0).getP()) {
			provinceList.add(cd.getN());
		}
		wheel1.setAdapter(new StringWheelAdapter(provinceList));
		wheel1.setCurrentItem(homeIdx1);
		wheel1.setCyclic(true);
		wheel1.setInterpolator(new AnticipateOvershootInterpolator());
		wheel1.addChangingListener(new OnWheelChangedListener() {
			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				homeIdx1 = newValue;
				homeIdx2 = 0;
				List<String> cityList = new ArrayList<String>();
				for (CityData cd : BaseActivity
						.getCountryList(getApplicationContext()).get(0).getP()
						.get(homeIdx1).getC()) {
					cityList.add(cd.getN());
				}
				wheel2.setAdapter(new StringWheelAdapter(cityList));
			}
		});

		List<String> cityList = new ArrayList<String>();
		for (CityData cd : BaseActivity.getCountryList(getApplicationContext())
				.get(0).getP().get(homeIdx1).getC()) {
			cityList.add(cd.getN());
		}
		wheel2.setAdapter(new StringWheelAdapter(cityList));
		wheel2.setCurrentItem(homeIdx2);
		wheel2.setCyclic(true);
		wheel2.setInterpolator(new AnticipateOvershootInterpolator());

		AlertDialog.Builder builder = new AlertDialog.Builder(MainTabBar.this);
		builder.setTitle(title);
		builder.setView(inputView);
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				homeIdx1 = wheel1.getCurrentItem();
				homeIdx2 = wheel2.getCurrentItem();
				if (TextUtils.isEmpty(BaseActivity
						.getCountryList(getApplicationContext()).get(0).getP()
						.get(homeIdx1).getN())) {
					inputEdit3.setText(BaseActivity
							.getCountryList(getApplicationContext()).get(0)
							.getP().get(homeIdx1).getC().get(homeIdx2).getN());
				} else {
					inputEdit3.setText(BaseActivity
							.getCountryList(getApplicationContext()).get(0)
							.getP().get(homeIdx1).getN()
							+ " "
							+ BaseActivity
									.getCountryList(getApplicationContext())
									.get(0).getP().get(homeIdx1).getC()
									.get(homeIdx2).getN());
				}
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
			}
		});
		builder.show();
	}

	private void showChooseCountryDialog4(String title,
			final TextView inputEdit4) {
		View inputView = getLayoutInflater().inflate(
				R.layout.dialog_wheel_2_view, null);
		final WheelView wheel1 = (WheelView) inputView
				.findViewById(R.id.wheel_1);
		final WheelView wheel2 = (WheelView) inputView
				.findViewById(R.id.wheel_2);

		List<String> provinceList = new ArrayList<String>();
		for (ProvinceData cd : BaseActivity
				.getCountryList(getApplicationContext()).get(0).getP()) {
			provinceList.add(cd.getN());
		}
		wheel1.setAdapter(new StringWheelAdapter(provinceList));
		wheel1.setCurrentItem(locIdx1);
		wheel1.setCyclic(true);
		wheel1.setInterpolator(new AnticipateOvershootInterpolator());
		wheel1.addChangingListener(new OnWheelChangedListener() {
			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				locIdx1 = newValue;
				locIdx2 = 0;
				List<String> cityList = new ArrayList<String>();
				for (CityData cd : BaseActivity
						.getCountryList(getApplicationContext()).get(0).getP()
						.get(locIdx1).getC()) {
					cityList.add(cd.getN());
				}
				wheel2.setAdapter(new StringWheelAdapter(cityList));
			}
		});

		List<String> cityList = new ArrayList<String>();
		for (CityData cd : BaseActivity.getCountryList(getApplicationContext())
				.get(0).getP().get(locIdx1).getC()) {
			cityList.add(cd.getN());
		}
		wheel2.setAdapter(new StringWheelAdapter(cityList));
		wheel2.setCurrentItem(locIdx2);
		wheel2.setCyclic(true);
		wheel2.setInterpolator(new AnticipateOvershootInterpolator());

		AlertDialog.Builder builder = new AlertDialog.Builder(MainTabBar.this);
		builder.setTitle(title);
		builder.setView(inputView);
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				locIdx1 = wheel1.getCurrentItem();
				locIdx2 = wheel2.getCurrentItem();
				if (TextUtils.isEmpty(BaseActivity
						.getCountryList(getApplicationContext()).get(0).getP()
						.get(locIdx1).getN())) {
					inputEdit4.setText(BaseActivity
							.getCountryList(getApplicationContext()).get(0)
							.getP().get(locIdx1).getC().get(locIdx2).getN());
				} else {
					inputEdit4.setText(BaseActivity
							.getCountryList(getApplicationContext()).get(0)
							.getP().get(locIdx1).getN()
							+ " "
							+ BaseActivity
									.getCountryList(getApplicationContext())
									.get(0).getP().get(locIdx1).getC()
									.get(locIdx2).getN());
				}
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
			}
		});
		builder.show();
	}

	/**
	 * 消息回执BroadcastReceiver
	 */
	private BroadcastReceiver ackMessageReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String msgid = intent.getStringExtra("msgid");
			String from = intent.getStringExtra("from");
			EMConversation conversation = EMChatManager.getInstance()
					.getConversation(from);
			if (conversation != null) {
				// 把message设为已读
				EMMessage msg = conversation.getMessage(msgid);
				if (msg != null) {
					msg.isAcked = true;
				}
			}
			abortBroadcast();
		}
	};

	/**
	 * 新消息广播接收者
	 * 
	 * 
	 */
	private class NewMessageBroadcastReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			// 消息id
			String msgId = intent.getStringExtra("msgid");
			// 收到这个广播的时候，message已经在db和内存里了，可以通过id获取mesage对象
			// EMMessage message =
			// EMChatManager.getInstance().getMessage(msgId);

			// 刷新bottom bar消息未读数
			updateUnreadLabel();
			// if (currentTabIndex == 0) {
			// // 当前页面如果为聊天历史页面，刷新此页面
			// if (chatHistoryFragment != null) {
			// chatHistoryFragment.refresh();
			// }
			// }
			// 注销广播，否则在ChatActivity中会收到这个广播
			abortBroadcast();

			if (currIdx == 1) {
				showCurrentBody(4);
				showCurrentBody(1);
			}
			checkHasNewUserInfo();
		}
	}

	/**
	 * 刷新未读消息数
	 */
	public void updateUnreadLabel() {
		final int count = getUnreadMsgCountTotal()
				+ getUnreadAddressCountTotal() + getRunReadInvited();
		// System.out.println("-----unread count-----"+count);
		if (count > 0) {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					unreadLabel.setText(String.valueOf(count));
					unreadLabel.setVisibility(View.VISIBLE);
				}
			});

		} else {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					unreadLabel.setVisibility(View.INVISIBLE);
				}
			});

		}
	}

	/**
	 * 获取未读消息数
	 * 
	 * @return
	 */
	public int getUnreadMsgCountTotal() {
		int unreadMsgCountTotal = 0;
		unreadMsgCountTotal = EMChatManager.getInstance().getUnreadMsgsCount();
		return unreadMsgCountTotal;
	}

	//
	private UserDao userDao;
	private InviteMessgeDao inviteMessgeDao;

	/***
	 * 联系人变化listener
	 * 
	 */
	// private class MyContactListener implements EMContactListener {
	//
	// @Override
	// public void onContactAdded(List<String> usernameList) {
	// // 保存增加的联系人
	// Map<String, User> localUsers =
	// BaseApplication.getInstance().getContactList();
	// Map<String, User> toAddUsers = new HashMap<String, User>();
	// for (String username : usernameList) {
	// User user = new User();
	// user.setUsername(username);
	// String headerName = null;
	// if (!TextUtils.isEmpty(user.getNick())) {
	// headerName = user.getNick();
	// } else {
	// headerName = user.getUsername();
	// }
	// if (username.equals(Constant.NEW_FRIENDS_USERNAME)) {
	// user.setHeader("");
	// } else if (Character.isDigit(headerName.charAt(0))) {
	// user.setHeader("#");
	// } else {
	// user.setHeader(HanziToPinyin.getInstance().get(headerName.substring(0,
	// 1)).get(0).target.substring(0, 1).toUpperCase());
	// char header = user.getHeader().toLowerCase().charAt(0);
	// if (header < 'a' || header > 'z') {
	// user.setHeader("#");
	// }
	// }
	// // 暂时有个bug，添加好友时可能会回调added方法两次
	// if (!localUsers.containsKey(username)) {
	// userDao.saveContact(user);
	// }
	// toAddUsers.put(username, user);
	// }
	// localUsers.putAll(toAddUsers);
	// // 刷新ui
	// // if (currentTabIndex == 1)
	// // contactListFragment.refresh();
	//
	// }
	//
	// @Override
	// public void onContactDeleted(List<String> usernameList) {
	// // 被删除
	// Map<String, User> localUsers =
	// BaseApplication.getInstance().getContactList();
	// for (String username : usernameList) {
	// localUsers.remove(username);
	// userDao.deleteContact(username);
	// inviteMessgeDao.deleteMessage(username);
	// }
	// // 刷新ui
	// // if (currentTabIndex == 1)
	// // contactListFragment.refresh();
	// updateUnreadLabel();
	//
	// }
	//
	// @Override
	// public void onContactInvited(String username, String reason) {
	// // 接到邀请的消息，如果不处理(同意或拒绝)，掉线后，服务器会自动再发过来，所以客户端不要重复提醒
	// List<InviteMessage> msgs = inviteMessgeDao.getMessagesList();
	// for (InviteMessage inviteMessage : msgs) {
	// if (inviteMessage.getFrom().equals(username)) {
	// return;
	// }
	// }
	// // 自己封装的javabean
	// InviteMessage msg = new InviteMessage();
	// msg.setFrom(username);
	// msg.setTime(System.currentTimeMillis());
	// msg.setReason(reason);
	// // Log.d(TAG, username + "请求加你为好友,reason: " + reason);
	// // 设置相应status
	// msg.setStatus(InviteMesageStatus.BEINVITEED);
	// notifyNewIviteMessage(msg);
	//
	// }
	//
	//
	//
	// @Override
	// public void onContactAgreed(String username) {
	// List<InviteMessage> msgs = inviteMessgeDao.getMessagesList();
	// for (InviteMessage inviteMessage : msgs) {
	// if (inviteMessage.getFrom().equals(username)) {
	// return;
	// }
	// }
	// // 自己封装的javabean
	// InviteMessage msg = new InviteMessage();
	// msg.setFrom(username);
	// msg.setTime(System.currentTimeMillis());
	// // Log.d(TAG, username + "同意了你的好友请求" );
	// msg.setStatus(InviteMesageStatus.BEAGREED);
	// notifyNewIviteMessage(msg);
	//
	// }
	//
	// @Override
	// public void onContactRefused(String username) {
	// //参考同意，被邀请实现此功能,demo未实现
	//
	// }
	//
	// }

	// protected void notifyNewIviteMessage(InviteMessage msg) {
	// // 保存msg
	// inviteMessgeDao.saveMessage(msg);
	// // 未读数加1
	// User user =
	// BaseApplication.getInstance().getContactList().get(Constant.NEW_FRIENDS_USERNAME);
	// user.setUnreadMsgCount(user.getUnreadMsgCount() + 1);
	// // 提示有新消息
	// EMNotifier.getInstance(getApplicationContext()).notifyOnNewMsg();
	//
	// // 刷新bottom bar消息未读数
	// updateUnreadAddressLable();
	// // 刷新好友页面ui
	// // if (currentTabIndex == 1)
	// // contactListFragment.refresh();
	// }

	// /**
	// * 刷新新的朋友消息数
	// */
	// public void updateUnreadAddressLable() {
	// runOnUiThread(new Runnable() {
	// public void run() {
	// int count = getUnreadAddressCountTotal();
	// if (count > 0) {
	// unreadLabel.setText(String.valueOf(count));
	// unreadLabel.setVisibility(View.VISIBLE);
	// } else {
	// unreadLabel.setVisibility(View.INVISIBLE);
	// }
	// }
	// });
	// }
	//
	// /**
	// * 获取未读新的朋友消息
	// *
	// * @return
	// */
	public int getUnreadAddressCountTotal() {
		// System.out.println("------getUnreadAddressCountTotal------"+BaseApplication.getInstance().getContactList().size());
		// int unreadAddressCountTotal = 0;
		/*
		 * if (BaseApplication.getInstance().getContactList().get(Constant.
		 * NEW_FRIENDS_USERNAME)!= null) unreadAddressCountTotal =
		 * BaseApplication
		 * .getInstance().getContactList().get(Constant.NEW_FRIENDS_USERNAME
		 * ).getUnreadMsgCount();
		 */
		updateInviteMessage();
		return invites.size();
	}

	public int getRunReadInvited() {
		updateInvitedMessage();
		return inviteds.size();
	}

	public static void updateInviteMessage() {
		RequestParams params = new RequestParams();
		params.put("uId", BaseActivity.getMyInfo(MainTabBar.s_instance)
				.getuId());
		HttpClient.getInstance().get(
				Constants.API_GET_CHART_MESSAGE,
				params,
				new MyResponseHandler(MainTabBar.s_instance,
						GroupMessageResponse.class) {
					@Override
					public void onSuccess(String result) {
						super.onSuccess(result);

						GroupMessageResponse res = (GroupMessageResponse) response;
						if (res.getData() != null) {
							MainTabBar.s_instance.invites = res.getData();
						} else {
							MainTabBar.s_instance.invites.clear();
						}
						int coun1 = 0;
						if (MainTabBar.s_instance.invites != null) {
							coun1 = MainTabBar.s_instance
									.getUnreadMsgCountTotal()
									+ MainTabBar.s_instance.inviteds.size()
									+ MainTabBar.s_instance.invites.size();
						} else {
							coun1 = MainTabBar.s_instance
									.getUnreadMsgCountTotal()
									+ MainTabBar.s_instance.inviteds.size();
						}
						final int count = coun1;
						// System.out.println("-----unread count-----"+count);
						String pushUserStr = ShareReferenceUtil
								.getPushUserInfoJson(MainTabBar.s_instance);
						if (!TextUtils.isEmpty(pushUserStr)) {
							List<UserInfoData> userInfoList = gson.fromJson(
									pushUserStr,
									new TypeToken<List<UserInfoData>>() {
									}.getType());
							if (MainTabBar.s_instance.invites != null) {
								for (GroupInvite invite : MainTabBar.s_instance.invites) {
									boolean isFound = false;
									for (UserInfoData userInfo : userInfoList) {
										if (userInfo.getuId().equals(
												invite.getFrom_user_id())) {
											isFound = true;
											break;
										}
									}
									if (!isFound) {
										MainTabBar.s_instance
												.getUserInfoById(invite
														.getFrom_user_id());
									}
								}
							}
						} else {
							if (MainTabBar.s_instance.invites != null) {
								for (GroupInvite invite : MainTabBar.s_instance.invites) {
									MainTabBar.s_instance
											.getUserInfoById(invite
													.getFrom_user_id());
								}
							}
						}
						if (count > 0) {
							MainTabBar.s_instance.runOnUiThread(new Runnable() {

								@Override
								public void run() {
									// TODO Auto-generated method stub
									MainTabBar.s_instance.unreadLabel
											.setText(String.valueOf(count));
									MainTabBar.s_instance.unreadLabel
											.setVisibility(View.VISIBLE);
								}
							});

						} else {
							MainTabBar.s_instance.runOnUiThread(new Runnable() {

								@Override
								public void run() {
									// TODO Auto-generated method stub
									MainTabBar.s_instance.unreadLabel
											.setVisibility(View.INVISIBLE);
								}
							});

						}

					}
				});
	}

	public static void updateInvitedMessage() {
		RequestParams params = new RequestParams();
		params.put("uId", BaseActivity.getMyInfo(MainTabBar.s_instance)
				.getuId());
		HttpClient.getInstance().get(
				Constants.API_GET_CHART_INVITE,
				params,
				new MyResponseHandler(MainTabBar.s_instance,
						GroupMessageResponse.class) {
					@Override
					public void onSuccess(String result) {
						super.onSuccess(result);

						GroupMessageResponse res = (GroupMessageResponse) response;
						if (res.getData() != null) {
							MainTabBar.s_instance.inviteds = res.getData();
						} else {
							MainTabBar.s_instance.inviteds.clear();
						}
						int coun1 = 0;
						if (MainTabBar.s_instance.inviteds != null) {
							coun1 = MainTabBar.s_instance
									.getUnreadMsgCountTotal()
									+ MainTabBar.s_instance.invites.size()
									+ MainTabBar.s_instance.inviteds.size();
						} else {
							coun1 = MainTabBar.s_instance
									.getUnreadMsgCountTotal()
									+ MainTabBar.s_instance.invites.size();
						}
						final int count = coun1;
						// System.out.println("-----unread count-----"+count);
						String pushUserStr = ShareReferenceUtil
								.getPushUserInfoJson(MainTabBar.s_instance);
						if (!TextUtils.isEmpty(pushUserStr)) {
							List<UserInfoData> userInfoList = gson.fromJson(
									pushUserStr,
									new TypeToken<List<UserInfoData>>() {
									}.getType());
							if (MainTabBar.s_instance.inviteds != null) {
								for (GroupInvite invite : MainTabBar.s_instance.inviteds) {
									boolean isFound = false;
									for (UserInfoData userInfo : userInfoList) {
										if (userInfo.getuId().equals(
												invite.getFrom_user_id())) {
											isFound = true;
											break;
										}
									}
									if (!isFound) {
										MainTabBar.s_instance
												.getUserInfoById(invite
														.getFrom_user_id());
									}
								}
							}
						} else {
							if (MainTabBar.s_instance.inviteds != null) {
								for (GroupInvite invite : MainTabBar.s_instance.inviteds) {
									MainTabBar.s_instance
											.getUserInfoById(invite
													.getFrom_user_id());
								}
							}
						}
						if (count > 0) {
							MainTabBar.s_instance.runOnUiThread(new Runnable() {

								@Override
								public void run() {
									// TODO Auto-generated method stub
									MainTabBar.s_instance.unreadLabel
											.setText(String.valueOf(count));
									MainTabBar.s_instance.unreadLabel
											.setVisibility(View.VISIBLE);
								}
							});

						} else {
							MainTabBar.s_instance.runOnUiThread(new Runnable() {

								@Override
								public void run() {
									// TODO Auto-generated method stub
									MainTabBar.s_instance.unreadLabel
											.setVisibility(View.INVISIBLE);
								}
							});

						}

					}
				});
	}

	/**
	 * 保存提示新消息
	 * 
	 * @param msg
	 */
	private void notifyNewIviteMessage(InviteMessage msg) {
		saveInviteMsg(msg);
		// 提示有新消息
		// HXSDKHelper.getInstance().getNotifier().viberateAndPlayTone(null);
		// 刷新bottom bar消息未读数
		updateUnreadLabel();
	}

	/**
	 * 保存邀请等msg
	 * 
	 * @param msg
	 */
	private void saveInviteMsg(InviteMessage msg) {
		// 保存msg
		inviteMessgeDao.saveMessage(msg);
		// 未读数加1
		User user = BaseApplication.getInstance().getContactList()
				.get(Constant.NEW_FRIENDS_USERNAME);
		if (user.getUnreadMsgCount() == 0)
			user.setUnreadMsgCount(user.getUnreadMsgCount() + 1);
	}

	public void handlerApply(String apply) {
		try {
			JSONObject object = new JSONObject(apply);
			String category = object.getString("category");
			if (category == "add") {
				InviteMessage msg = new InviteMessage();
				msg.setFrom(object.getString("uid"));
				msg.setTime(System.currentTimeMillis());
				msg.setGroupId(object.getString("groupid"));
				msg.setGroupName(object.getString("groupname"));
				msg.setReason(object.getString("approvcontent"));
				msg.setStatus(InviteMesageStatus.BEAPPLYED);
				notifyNewIviteMessage(msg);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * MyGroupChangeListener
	 */
	private class MyGroupChangeListener implements EMGroupChangeListener {

		@Override
		public void onInvitationReceived(String groupId, String groupName,
				String inviter, String reason) {
			boolean hasGroup = false;
			for (EMGroup group : EMGroupManager.getInstance().getAllGroups()) {
				if (group.getGroupId().equals(groupId)) {
					hasGroup = true;
					break;
				}
			}
			if (!hasGroup)
				return;

			// 被邀请

		}

		@Override
		public void onInvitationAccpted(String groupId, String inviter,
				String reason) {

		}

		@Override
		public void onInvitationDeclined(String groupId, String invitee,
				String reason) {

		}

		@Override
		public void onUserRemoved(String groupId, String groupName) {
			// 提示用户被T了，demo省略此步骤
			// 刷新ui

		}

		@Override
		public void onGroupDestroy(String groupId, String groupName) {
			// 群被解散
			// 提示用户群被解散,demo省略
			// 刷新ui

		}

		@Override
		public void onApplicationReceived(String groupId, String groupName,
				String applyer, String reason) {
			// 用户申请加入群聊
			// System.out.println(applyer+"申请加入群："+groupId+groupName+reason);
			InviteMessage msg = new InviteMessage();
			msg.setFrom(applyer);
			msg.setTime(System.currentTimeMillis());
			msg.setGroupId(groupId);
			msg.setGroupName(groupName);
			msg.setReason(reason);
			msg.setStatus(InviteMesageStatus.BEAPPLYED);
			notifyNewIviteMessage(msg);
		}

		@Override
		public void onApplicationAccept(String groupId, String groupName,
				String accepter) {
			// 加群申请被同意
			EMMessage msg = EMMessage.createReceiveMessage(Type.TXT);
			msg.setChatType(ChatType.GroupChat);
			msg.setFrom(accepter);
			msg.setTo(groupId);
			msg.setMsgId(UUID.randomUUID().toString());
			msg.addBody(new TextMessageBody(accepter + "同意了你的加群申请"));
			// 保存同意消息
			EMChatManager.getInstance().saveMessage(msg);
			// 提醒新消息
			// HXSDKHelper.getInstance().getNotifier().viberateAndPlayTone(msg);

			runOnUiThread(new Runnable() {
				public void run() {
					updateUnreadLabel();
					// 刷新ui

				}
			});
		}

		@Override
		public void onApplicationDeclined(String groupId, String groupName,
				String decliner, String reason) {
			// 加群申请被拒绝，demo未实现
			System.out.println(decliner + "拒绝您加入群：" + groupId + groupName);

		}

	}

	private void checkHasNewUserInfo() {
		String pushUserStr = ShareReferenceUtil
				.getPushUserInfoJson(getApplicationContext());
		if (!TextUtils.isEmpty(pushUserStr)) {
			System.out.println("MainTab Start");
			if (EMChatDB.getInstance() != null) {
				Gson gson = new Gson();
				List<UserInfoData> userInfoList = gson.fromJson(pushUserStr,
						new TypeToken<List<UserInfoData>>() {
						}.getType());
				List<String> userNameIdList = EMChatDB.getInstance()
						.findAllParticipantsWithMsg();
				for (String userNameId : userNameIdList) {
					boolean isFound = false;
					for (UserInfoData userInfo : userInfoList) {
						if (userInfo.getuId().equals(userNameId)) {
							isFound = true;
							break;
						}
					}
					if (!isFound) {
						getUserInfoById(userNameId);
					}
				}
				for (EMGroup group : EMGroupManager.getInstance()
						.getAllGroups()) {
					EMConversation conversation = EMChatManager.getInstance()
							.getConversation(group.getGroupId());
					if (conversation.getMsgCount() > 0) {
						List<EMMessage> members = conversation.getAllMessages();
						for (EMMessage message : members) {
							boolean isFound = false;
							for (UserInfoData userInfo : userInfoList) {
								if (userInfo.getuId().equals(message.getFrom())) {
									isFound = true;
									break;
								}
							}
							if (!isFound) {
								getUserInfoById(message.getFrom());
							}
						}
					}

				}

			}
		} else {
			System.out.println("MainTab End");
			if (EMChatDB.getInstance() != null) {
				System.out.println("MainTab End1");
				List<String> userNameIdList = EMChatDB.getInstance()
						.findAllParticipantsWithMsg();
				for (String userNameId : userNameIdList) {
					getUserInfoById(userNameId);
				}
				System.out.println("MainTab End2");
				for (EMGroup group : EMGroupManager.getInstance()
						.getAllGroups()) {
					System.out.println("MainTab End22");
					EMConversation conversation = EMChatManager.getInstance()
							.getConversation(group.getGroupId());
					if (conversation.getMsgCount() > 0) {
						System.out.println("MainTab End23");
						List<EMMessage> members = conversation.getAllMessages();
						for (EMMessage message : members) {
							System.out.println("MainTab End:"
									+ message.getFrom());
							getUserInfoById(message.getFrom());
						}
					}
				}
				System.out.println("MainTab End3");
			}
		}
		String pushGroupStr = ShareReferenceUtil
				.getPushGroupInfoJson(getApplicationContext());
		if (!TextUtils.isEmpty(pushGroupStr)) {
			Gson gson = new Gson();
			List<GroupInfo> groupInfoList = gson.fromJson(pushGroupStr,
					new TypeToken<List<GroupInfo>>() {
					}.getType());
			for (EMGroup group : EMGroupManager.getInstance().getAllGroups()) {
				boolean isFound = false;
				for (GroupInfo userInfo : groupInfoList) {
					if (userInfo.getGroupid()!=null&&userInfo.getGroupid().equals(group.getGroupId())) {
						isFound = true;
						break;
					}
				}
				if (!isFound) {
					getGroupInfoById(group.getGroupId());
				}
			}
		} else {
			for (EMGroup group : EMGroupManager.getInstance().getAllGroups()) {
				getGroupInfoById(group.getGroupId());
			}
		}
	}

	private void getGroupInfoById(String gid) {
		RequestParams params = new RequestParams();
		params.put("uId", BaseActivity.getMyInfo(getApplicationContext())
				.getuId());
		params.put("groupid", gid);
		HttpClient.getInstance().get(Constants.API_GET_CHART_DETAIL, params,
				gidHandler);
	}

	private AsyncHttpResponseHandler gidHandler = new AsyncHttpResponseHandler() {
		@Override
		public void onFailure(Throwable arg0, String arg1) {
			super.onFailure(arg0, arg1);
		}

		@Override
		public void onSuccess(String result) {
			// TODO Auto-generated method stub
			super.onSuccess(result);

			if (!TextUtils.isEmpty(result)) {
				try {
					Gson gson = new Gson();
					GroupDetailsResponse response = gson.fromJson(result,
							GroupDetailsResponse.class);
					if (response.getErrNo() != null
							&& response.getErrNo().equals("0")) {
						GroupInfo userInfo = response.getData();
						// System.out.println("----userInfo.getuName()----"+userInfo.getuName());
						String pushGroupStr = ShareReferenceUtil
								.getPushGroupInfoJson(getApplicationContext());
						if (!TextUtils.isEmpty(pushGroupStr)) {
							List<GroupInfo> userInfoList = gson.fromJson(
									pushGroupStr,
									new TypeToken<List<GroupInfo>>() {
									}.getType());
							userInfoList.add(userInfo);
							ShareReferenceUtil.savePushGroupInfoJson(
									getApplicationContext(),
									gson.toJson(userInfoList));
						} else {
							List<GroupInfo> userInfoList = new ArrayList<GroupInfo>();
							userInfoList.add(userInfo);
							ShareReferenceUtil.savePushGroupInfoJson(
									getApplicationContext(),
									gson.toJson(userInfoList));
						}
						ChatHistoryActivity.needRefresh = true;
						if (currIdx == 1) {
							showCurrentBody(0);
							showCurrentBody(1);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

	};

	private void getUserInfoById(String uid) {
		RequestParams params = new RequestParams();
		params.put("uid", uid);
		HttpClient.getInstance().get(Constants.API_GET_USER_INFO_URL, params,
				uidHandler);
	}

	private AsyncHttpResponseHandler uidHandler = new AsyncHttpResponseHandler() {
		@Override
		public void onFailure(Throwable arg0, String arg1) {
			super.onFailure(arg0, arg1);
		}

		@Override
		public void onSuccess(String result) {
			// TODO Auto-generated method stub
			super.onSuccess(result);

			System.out.println("----on get user info success----" + result);
			if (!TextUtils.isEmpty(result)) {
				try {
					Gson gson = new Gson();
					UserInfoResponse response = gson.fromJson(result,
							UserInfoResponse.class);
					if (response.getErrNo() != null
							&& response.getErrNo().equals("0")) {
						UserInfoData userInfo = response.getData();
						// System.out.println("----userInfo.getuName()----"+userInfo.getuName());
						String pushUserStr = ShareReferenceUtil
								.getPushUserInfoJson(getApplicationContext());
						if (!TextUtils.isEmpty(pushUserStr)) {
							List<UserInfoData> userInfoList = gson.fromJson(
									pushUserStr,
									new TypeToken<List<UserInfoData>>() {
									}.getType());
							userInfoList.add(userInfo);
							ShareReferenceUtil.savePushUserInfoJson(
									getApplicationContext(),
									gson.toJson(userInfoList));
						} else {
							List<UserInfoData> userInfoList = new ArrayList<UserInfoData>();
							userInfoList.add(userInfo);
							ShareReferenceUtil.savePushUserInfoJson(
									getApplicationContext(),
									gson.toJson(userInfoList));
						}
						ChatHistoryActivity.needRefresh = true;
						if (currIdx == 1) {
							showCurrentBody(0);
							showCurrentBody(1);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

	};

	private PopupWindow popupWindow;

	private void showPopUp() {
		View popupView = getLayoutInflater().inflate(
				R.layout.popup_more_menu_view, null);
		popupWindow = new PopupWindow(popupView, getWindowManager()
				.getDefaultDisplay().getWidth(), getWindowManager()
				.getDefaultDisplay().getHeight());
		popupView.findViewById(R.id.btn_popup_menu_close).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View arg0) {
						popupWindow.dismiss();
					}
				});
		popupView.findViewById(R.id.btn_func_1).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View arg0) {
						popupWindow.dismiss();
						startActivity(new Intent(getApplicationContext(),
								ZhidaoActivity.class));
					}
				});
		popupView.findViewById(R.id.btn_func_2).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View arg0) {
						popupWindow.dismiss();
						startActivity(new Intent(getApplicationContext(),
								FlyTogetherActivity.class));
					}
				});
		popupView.findViewById(R.id.btn_func_3).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View arg0) {
						popupWindow.dismiss();
						startActivity(new Intent(getApplicationContext(),
								HouseInfoListActivity.class));
					}
				});
		popupView.findViewById(R.id.btn_func_4).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View arg0) {
						popupWindow.dismiss();
						startActivity(new Intent(getApplicationContext(),
								MutualTransactionList2Activity.class));
					}
				});
		popupView.findViewById(R.id.btn_func_5).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View arg0) {
						popupWindow.dismiss();
						startActivity(new Intent(getApplicationContext(),
								MutualTransactionList3Activity.class));
					}
				});
		popupView.findViewById(R.id.btn_func_6).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View arg0) {
						popupWindow.dismiss();
						startActivity(new Intent(getApplicationContext(),
								MutualTransactionList1Activity.class));
					}
				});
		popupWindow.update();
		popupWindow.setFocusable(true);
		popupWindow.setTouchable(true);
		popupWindow.showAtLocation(findViewById(R.id.main_top_layout),
				Gravity.CENTER, 0, 0);
	}

	private Boolean openGPSSettings() {
		LocationManager alm = (LocationManager) this
				.getSystemService(Context.LOCATION_SERVICE);
		if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
			// Toast.makeText(this, "GPS模块正常", Toast.LENGTH_SHORT).show();
			return true;
		} else {

			// Toast.makeText(this, "请开启GPS！", Toast.LENGTH_SHORT).show();
			return false;
		}
	}

	private LocationManager locationManager;
	private Location location;
	private String provider;

	private void getLocation() {

		if (!openGPSSettings()) {
			return;
		}
		// 获取位置管理服务
		locationManager = (LocationManager) this
				.getSystemService(Context.LOCATION_SERVICE);

		// getting GPS status
		Boolean isGPSEnabled = locationManager
				.isProviderEnabled(LocationManager.GPS_PROVIDER);

		// getting network status
		Boolean isNetworkEnabled = locationManager
				.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

		if (!isGPSEnabled && !isNetworkEnabled) {
			// no network provider is enabled
		} else {

			if (isGPSEnabled) {
				locationManager.requestLocationUpdates(
						LocationManager.GPS_PROVIDER, 1000, (float) 1000.0,
						locationListener);
				Log.d("activity", "LOC Network Enabled");
				if (locationManager != null) {
					location = locationManager
							.getLastKnownLocation(LocationManager.GPS_PROVIDER);
					while (location == null) {
						locationManager.requestLocationUpdates(
								LocationManager.GPS_PROVIDER, 1000,
								(float) 1000.0, locationListener);
						location = locationManager
								.getLastKnownLocation(LocationManager.GPS_PROVIDER);
					}
					if (location != null) {
						Log.d("activity", "LOC by Network");
						ShareReferenceUtil.saveLocationLatitude(
								getApplicationContext(), location.getLatitude()
										+ "");
						ShareReferenceUtil.saveLocationLontitude(
								getApplicationContext(),
								location.getLongitude() + "");
						// double latitude = location.getLatitude();
						// double longitude = location.getLongitude();
					}
				}
			}
			// if GPS Enabled get lat/long using GPS Services
			if (isNetworkEnabled) {
				if (location == null) {
					locationManager.requestLocationUpdates(
							LocationManager.NETWORK_PROVIDER, 1000,
							(float) 1000.0, locationListener);
					Log.d("activity", "RLOC: GPS Enabled");
					if (locationManager != null) {
						location = locationManager
								.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
						if (location != null) {
							Log.d("activity", "RLOC: loc by GPS");

							ShareReferenceUtil.saveLocationLatitude(
									getApplicationContext(),
									location.getLatitude() + "");
							ShareReferenceUtil.saveLocationLontitude(
									getApplicationContext(),
									location.getLongitude() + "");
						}
					}
				}
			}
		}
		/*
		 * String serviceName = Context.LOCATION_SERVICE; locationManager =
		 * (LocationManager) this.getSystemService(serviceName);
		 * //locationManager.setTestProviderEnabled("gps", true); // 查找到服务信息
		 * Criteria criteria = new Criteria();
		 * criteria.setAccuracy(Criteria.ACCURACY_FINE); // 高精度
		 * criteria.setAltitudeRequired(false);
		 * criteria.setBearingRequired(false); criteria.setCostAllowed(true);
		 * criteria.setPowerRequirement(Criteria.POWER_LOW); // 低功耗
		 * 
		 * provider = locationManager.getBestProvider(criteria, true); //
		 * 获取GPS信息 Location location =
		 * locationManager.getLastKnownLocation(provider); // 通过GPS获取位置
		 * updateToNewLocation(location); //
		 * 设置监听器，自动更新的最小时间为间隔N秒(1秒为1*1000，这样写主要为了方便)或最小位移变化超过N米
		 * locationManager.requestLocationUpdates(provider, 1000, (float)
		 * 1000.0, locationListener);
		 */
	}

	private String TAG = "MainTabBar";
	private LocationListener locationListener;

	private void updateToNewLocation(Location location) {

		if (location != null) {
			double latitude = location.getLatitude();
			double longitude = location.getLongitude();
			ShareReferenceUtil.saveLocationLatitude(getApplicationContext(),
					latitude + "");
			ShareReferenceUtil.saveLocationLontitude(getApplicationContext(),
					longitude + "");
		} else {

		}

	}

	private MyReceiver receiver;

	public static class MyReceiver extends BroadcastReceiver {

		private final Handler handler; // Handler used to execute code on the UI
										// thread

		public MyReceiver(Handler handler) {
			this.handler = handler;
		}

		@Override
		public void onReceive(final Context context, Intent intent) {
			// Post the UI updating code to our Handler
			handler.post(new Runnable() {
				@Override
				public void run() {
					updateInviteMessage();
				}
			});
		}
	}
}
